/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package serveur;
import com.sun.org.apache.xerces.internal.util.XMLChar;
import java.net.*;
import java.util.*;
import java.io.*;

public class Authentification implements Runnable {
    private Socket socket;
    private PrintWriter out = null;
    private BufferedReader in = null;
    private String login = "client", pass = "lol";
    public boolean authentifier = false;
    public Thread t2;
    
    public Authentification(Socket s){
        socket = s;
    }
    public void run() {
        
        try{
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());
         while(!authentifier){
             out.println("Entre votre login :");
             out.flush();
             login = in.readLine();
             
             out.println("Entrez votre mot de passe :");
             out.flush();
             pass = in.readLine();
             
             if(isValid(login,pass)){
                 out.println("connecte");
                 System.out.println(login+" vient de se connecter ");
                 out.flush();
                 authentifier = true;
             }
             else {out.println("erreur"); out.flush();}
           }
            t2 = new Thread(new Chat_ClientServeur(socket,login));
            t2.start();
        }catch (IOException e){
           System.err.println(login+" ne répond pas !");
        }
    }
    
    private static boolean isValid(String login, String pass){
        
        boolean connexion = false;
        try{
            Scanner sc = new Scanner(new File("C:\\Users\\PaulS\\Desktop\\BTS SIO 2\\SLAM 4\\JAVA\\Serveur\\src\\serveur\\client.txt"));
            
            while(sc.hasNext()){
                if(sc.nextLine().equals(login+" "+pass)){
                    connexion=true;
                }
            }
        }catch (FileNotFoundException e){
            System.err.println("Le fichier n'existe pas !");
        }
       return connexion;
    }
}
